package com.gamex.battle.server;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundMessageHandlerAdapter;

import java.util.logging.Level;
import java.util.logging.Logger;

import com.gamex.battle.common.Battle;
import com.gamex.battle.server.service.BattleService;


public class BattleServerHandler extends ChannelInboundMessageHandlerAdapter<Battle> {

	 private static final Logger logger = Logger.getLogger(BattleServerHandler.class.getName());
	 
	
	@Override
	public void messageReceived(ChannelHandlerContext ctx, Battle info) throws Exception {
		doService(info, ctx.channel());
	}
	
	private void doService(Battle info, Channel ch){
		BattleService.routingService(info, ch);
		
	}
	
	@Override
    public void channelActive(final ChannelHandlerContext ctx) throws Exception {
		System.out.println("=====================================================================");
		System.out.println(">>>>>> Channel " + ctx.channel().id() + " is Active now!(active user cnt : " + (BattleService.users.size() + 1) +")");
		System.out.println("=====================================================================");
    }
	
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		BattleService.remveUserInfoByChannelId(ctx.channel().id());
		System.out.println("=====================================================================");
		System.out.println(">>>>>> Channel " + ctx.channel().id() + " is Inactive now!(active user cnt : " + BattleService.users.size() +")");
		System.out.println("=====================================================================");
	}
            
	@Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
       // logger.log(Level.WARNING, "Exception", cause);
        BattleService.remveUserInfoByChannelId(ctx.channel().id());
        ctx.close();
    }

}
